﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Moneymatters
{
    internal static class NumberToWords
    {
        private static string[] TensWord = new string[]{string.Empty, string.Empty, "Twenty",
            "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
        
        private static string[] OnesWord = new string[] {
            "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven",
            "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen",
            "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
        
        private static string[] GroupNames = new string[]{
            "lakh", "thousand",""};
        
        public static string GetNumberAsWords(decimal number)
        {
            StringBuilder sb = new StringBuilder();
            if (number > 9999999)
            {
                decimal crores = (long)number / 10000000;
                sb.Append(GetNumberAsWords(crores) + (crores == 1 ? " crore" : " crore "));
                number = number % 10000000;
            }

            string numberString = number.ToString("00,00,000",
                System.Globalization.CultureInfo.GetCultureInfo("hi-IN"));
            string[] numberParts = numberString.Split(',');
            for (int i = 0; i < numberParts.Length; i++)
            {
                if (int.Parse(numberParts[i]) == 0)
                    continue;
                string groupAsWords = GroupInWords(numberParts[i]);
                if (sb.Length != 0 && numberParts[i].Length == 3 && !groupAsWords.Contains(" and "))
                {
                    sb.Append(" and ");
                }
                sb.Append(groupAsWords + " " + GroupNames[i]);
                sb.Append(numberParts[i].Length == 2 && numberParts[i] != "01" ? " " : " ");
            }
            return sb.ToString().Trim();
        }
        
        private static string GroupInWords(string numGroup)
        {
            string groupWords = "";
            if (numGroup.Length == 3)
            {
                if (numGroup[0] != '0')
                {
                    int hundreds = int.Parse(numGroup.Substring(0, 1));
                    groupWords = OnesWord[hundreds] + " hundred ";
                    if (int.Parse(numGroup.Substring(1)) != 0)
                        groupWords += "and ";
                }
                numGroup = numGroup.Substring(1);
            }
            int tens = int.Parse(numGroup.Substring(0, 1));
            if (tens > 1)
            {
                groupWords += TensWord[tens] + " ";
                numGroup = numGroup.Substring(1);
            }
            int ones = int.Parse(numGroup);
            if (ones > 0)
                groupWords += OnesWord[ones];
            return groupWords;
        }
    }
}
